<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Fast Bridge - 客户端页面</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 20px;
        background: #e8f4fd;
      }
      .container {
        max-width: 800px;
        margin: 0 auto;
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }
      .status {
        padding: 10px;
        border-radius: 4px;
        margin: 10px 0;
      }
      .status.connected {
        background: #d4edda;
        color: #155724;
      }
      .status.disconnected {
        background: #f8d7da;
        color: #721c24;
      }
      .controls {
        display: flex;
        gap: 10px;
        margin: 20px 0;
        flex-wrap: wrap;
      }
      button {
        padding: 10px 20px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
      }
      .btn-primary {
        background: #007bff;
        color: white;
      }
      .btn-success {
        background: #28a745;
        color: white;
      }
      .btn-warning {
        background-color: #ffc107;
        color: #000;
      }
      .btn-info {
        background-color: #17a2b8;
        color: white;
      }
      .btn-secondary {
        background-color: #6c757d;
        color: white;
      }
      .log {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 10px;
        height: 200px;
        overflow-y: auto;
        font-family: monospace;
        font-size: 12px;
      }
      .demo-section {
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 15px;
        margin: 15px 0;
      }
      .demo-section h3 {
        margin-top: 0;
        color: #495057;
      }
      .form-group {
        margin: 10px 0;
      }
      label {
        display: inline-block;
        width: 80px;
        font-weight: bold;
      }
      input,
      select {
        padding: 5px;
        border: 1px solid #ced4da;
        border-radius: 4px;
        width: 100px;
      }
      .result {
        background: #e9ecef;
        padding: 10px;
        border-radius: 4px;
        margin: 10px 0;
        font-family: monospace;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>🎯 Fast Bridge - 客户端页面</h1>

      <div id="status" class="status disconnected">状态: 正在连接...</div>

      <div class="controls">
        <button id="callHostBtn" class="btn-primary" disabled>调用宿主方法</button>
        <button id="emitBtn" class="btn-success" disabled>发送事件</button>
        <button id="calculateBtn" class="btn-info" disabled>计算器</button>
        <button id="errorBtn" class="btn-warning" disabled>模拟错误</button>
      </div>

      <div class="demo-section">
        <h3>📊 宿主信息</h3>
        <button id="getHostInfoBtn" class="btn-primary" disabled>获取宿主信息</button>
        <div id="hostInfo" class="result">等待连接...</div>
      </div>

      <div class="demo-section">
        <h3>🧮 计算器</h3>
        <div class="form-group">
          <label>数字 A:</label>
          <input type="number" id="numA" value="10" />
        </div>
        <div class="form-group">
          <label>操作:</label>
          <select id="operation">
            <option value="+">加法 (+)</option>
            <option value="-">减法 (-)</option>
            <option value="*">乘法 (*)</option>
            <option value="/">除法 (/)</option>
          </select>
        </div>
        <div class="form-group">
          <label>数字 B:</label>
          <input type="number" id="numB" value="5" />
        </div>
        <button id="calculateBtn2" class="btn-info" disabled>计算</button>
        <div id="calcResult" class="result">等待连接...</div>
      </div>

      <div class="demo-section">
        <h3>⚡ 异步方法测试</h3>
        <div class="controls">
          <button id="fetchDataBtn" class="btn-primary" disabled>调用宿主 fetchUserData</button>
          <button id="performTaskBtn" class="btn-success" disabled>调用宿主 processData</button>
          <button id="validateBtn" class="btn-warning" disabled>调用宿主 simulateError</button>
          <button id="longOpBtn" class="btn-info" disabled>调用宿主 simulateLongOperation</button>
          <button id="streamDataBtn" class="btn-secondary" disabled>调用宿主 streamData</button>
        </div>
        <div id="asyncResult" class="result">等待连接...</div>
      </div>

      <div class="demo-section">
        <h3>📝 日志</h3>
        <div id="log" class="log"></div>
      </div>
    </div>

    <script type="module">
      import { FastBridge } from "../../src/index.js";

      // 获取 DOM 元素
      const statusEl = document.getElementById("status");
      const callHostBtn = document.getElementById("callHostBtn");
      const emitBtn = document.getElementById("emitBtn");
      const calculateBtn = document.getElementById("calculateBtn");
      const errorBtn = document.getElementById("errorBtn");
      const getHostInfoBtn = document.getElementById("getHostInfoBtn");
      const calculateBtn2 = document.getElementById("calculateBtn2");
      const logEl = document.getElementById("log");
      const hostInfoEl = document.getElementById("hostInfo");
      const calcResultEl = document.getElementById("calcResult");
      const fetchDataBtn = document.getElementById("fetchDataBtn");
      const performTaskBtn = document.getElementById("performTaskBtn");
      const validateBtn = document.getElementById("validateBtn");
      const longOpBtn = document.getElementById("longOpBtn");
      const streamDataBtn = document.getElementById("streamDataBtn");
      const asyncResultEl = document.getElementById("asyncResult");

      // 日志函数
      function log(message, type = "info") {
        const time = new Date().toLocaleTimeString();
        const logEntry = document.createElement("div");
        logEntry.style.color =
          type === "error" ? "red" : type === "warn" ? "orange" : type === "success" ? "green" : "black";
        logEntry.textContent = `[${time}] ${message}`;
        logEl.appendChild(logEntry);
        logEl.scrollTop = logEl.scrollHeight;
      }

      // 创建 FastBridge 实例
      const bridge = new FastBridge({
        namespace: "demo",
        debug: true,
      });

      // 注册方法供宿主调用
      bridge.register("getClientInfo", async (params) => {
        log(`宿主请求客户端信息: ${JSON.stringify(params)}`);
        return {
          title: "Fast Bridge 客户端页面",
          timestamp: Date.now(),
          url: window.location.href,
          userAgent: navigator.userAgent,
          ...params,
        };
      });

      bridge.register("getClientStats", async () => {
        const stats = bridge.getMessageStats();
        return {
          stats,
          timestamp: Date.now(),
        };
      });

      // 添加异步方法示例
      bridge.register("fetchData", async (params) => {
        const { type, id } = params;
        log(`宿主请求数据: type=${type}, id=${id}`);

        // 模拟异步网络请求
        await new Promise((resolve) => setTimeout(resolve, 1200));

        // 模拟不同类型的数据
        let data;
        switch (type) {
          case "user":
            data = {
              id,
              name: `用户${id}`,
              email: `user${id}@client.com`,
              role: "client",
              permissions: ["read", "write"],
            };
            break;
          case "product":
            data = {
              id,
              name: `产品${id}`,
              price: Math.floor(Math.random() * 1000) + 100,
              category: "电子产品",
              inStock: Math.random() > 0.3,
            };
            break;
          case "order":
            data = {
              id,
              status: "processing",
              items: [
                { name: "商品A", quantity: 2, price: 50 },
                { name: "商品B", quantity: 1, price: 100 },
              ],
              total: 200,
              createdAt: new Date().toISOString(),
            };
            break;
          default:
            throw new Error(`不支持的数据类型: ${type}`);
        }

        log(`返回数据: ${JSON.stringify(data)}`);
        return data;
      });

      bridge.register("performTask", async (params) => {
        const { task, duration = 1000 } = params;
        log(`宿主请求执行任务: ${task}, 预计耗时: ${duration}ms`);

        // 模拟任务执行时间
        await new Promise((resolve) => setTimeout(resolve, duration));

        // 模拟任务结果
        const result = {
          task,
          status: "completed",
          result: `任务 ${task} 执行成功`,
          duration,
          timestamp: Date.now(),
        };

        log(`任务完成: ${JSON.stringify(result)}`);
        return result;
      });

      bridge.register("validateInput", async (params) => {
        const { data, rules } = params;
        log(`宿主请求验证输入: ${JSON.stringify(data)}`);

        // 模拟验证过程
        await new Promise((resolve) => setTimeout(resolve, 600));

        const errors = [];

        // 模拟验证规则
        if (rules.includes("required") && (!data || data.trim() === "")) {
          errors.push("字段不能为空");
        }

        if (rules.includes("email") && data && !data.includes("@")) {
          errors.push("邮箱格式不正确");
        }

        if (rules.includes("minLength") && data && data.length < 3) {
          errors.push("长度不能少于3个字符");
        }

        const result = {
          valid: errors.length === 0,
          errors,
          data,
          timestamp: Date.now(),
        };

        log(`验证结果: ${JSON.stringify(result)}`);
        return result;
      });

      bridge.register("batchProcessData", async (params) => {
        const { count = 50, delay = 100 } = params;
        log(`宿主请求批量处理数据: 数量=${count}, 延迟=${delay}ms`);

        const results = [];
        const startTime = Date.now();

        for (let i = 1; i <= count; i++) {
          // 模拟每条数据的处理
          await new Promise((resolve) => setTimeout(resolve, delay));

          const itemResult = {
            id: i,
            data: `数据项_${i}`,
            processed: true,
            timestamp: Date.now(),
            value: Math.floor(Math.random() * 1000),
          };

          results.push(itemResult);

          // 每10条数据记录一次进度
          if (i % 10 === 0) {
            log(`批量处理进度: ${i}/${count} (${Math.round((i / count) * 100)}%)`);
          }
        }

        const endTime = Date.now();
        const totalTime = endTime - startTime;

        const finalResult = {
          totalItems: count,
          processedItems: results.length,
          totalTime,
          averageTimePerItem: totalTime / count,
          results,
          completed: true,
          timestamp: endTime,
        };

        log(`批量处理完成: 处理了 ${count} 条数据，总耗时 ${totalTime}ms`);
        return finalResult;
      });

      // 监听宿主事件
      bridge.on("hostMessage", (data) => {
        log(`收到宿主消息: ${JSON.stringify(data)}`, "success");
      });

      bridge.on("updateUI", (data) => {
        log(`收到UI更新: ${JSON.stringify(data)}`);
        // 这里可以更新UI
      });

      // 监听连接状态变化
      bridge.onConnectionChange((connected) => {
        statusEl.textContent = `状态: ${connected ? "已连接" : "未连接"}`;
        statusEl.className = `status ${connected ? "connected" : "disconnected"}`;

        // 更新按钮状态
        const connectedButtons = [
          callHostBtn,
          emitBtn,
          calculateBtn,
          errorBtn,
          getHostInfoBtn,
          calculateBtn2,
          fetchDataBtn,
          performTaskBtn,
          validateBtn,
          longOpBtn,
          streamDataBtn,
        ];
        connectedButtons.forEach((btn) => (btn.disabled = !connected));

        log(`连接状态变化: ${connected ? "已连接" : "未连接"}`);

        if (connected) {
          // 连接成功后通知宿主
          bridge.emit("clientReady", {
            timestamp: Date.now(),
            url: window.location.href,
          });
        }
      });

      // 事件处理
      callHostBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("getHostInfo", {
            includeDetails: true,
            timestamp: Date.now(),
          });
          log(`调用宿主方法成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          log(`调用宿主方法失败: ${error.message}`, "error");
        }
      });

      emitBtn.addEventListener("click", () => {
        const eventData = {
          message: "来自客户端的问候",
          timestamp: Date.now(),
          random: Math.random(),
        };
        bridge.emit("userAction", eventData);
        log(`发送事件到宿主: ${JSON.stringify(eventData)}`);
      });

      calculateBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("calculate", {
            a: 100,
            b: 50,
            operation: "+",
          });
          log(`计算成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          log(`计算失败: ${error.message}`, "error");
        }
      });

      errorBtn.addEventListener("click", () => {
        bridge.emit("clientError", {
          message: "这是一个模拟错误",
          timestamp: Date.now(),
          type: "simulation",
        });
        log("发送模拟错误事件", "warn");
      });

      getHostInfoBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("getHostInfo", {
            includeUserAgent: true,
            timestamp: Date.now(),
          });
          hostInfoEl.textContent = JSON.stringify(result, null, 2);
          log("获取宿主信息成功", "success");
        } catch (error) {
          hostInfoEl.textContent = `错误: ${error.message}`;
          log(`获取宿主信息失败: ${error.message}`, "error");
        }
      });

      calculateBtn2.addEventListener("click", async () => {
        const a = parseFloat(document.getElementById("numA").value);
        const b = parseFloat(document.getElementById("numB").value);
        const operation = document.getElementById("operation").value;

        try {
          const result = await bridge.call("calculate", { a, b, operation });
          calcResultEl.textContent = `${a} ${operation} ${b} = ${result.result}`;
          log(`计算成功: ${a} ${operation} ${b} = ${result.result}`, "success");
        } catch (error) {
          calcResultEl.textContent = `错误: ${error.message}`;
          log(`计算失败: ${error.message}`, "error");
        }
      });

      fetchDataBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("fetchUserData", {
            userId: Math.floor(Math.random() * 10) + 1,
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`异步方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`异步方法调用失败: ${error.message}`, "error");
        }
      });

      performTaskBtn.addEventListener("click", async () => {
        try {
          const testData = [5, 2, 8, 1, 9, 3];
          const result = await bridge.call("processData", {
            data: testData,
            operation: "sort",
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`异步方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`异步方法调用失败: ${error.message}`, "error");
        }
      });

      validateBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("simulateError", {
            errorType: "validation",
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`异步方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`异步方法调用失败: ${error.message}`, "error");
        }
      });

      longOpBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("simulateLongOperation", {
            operation: "exampleLongOperation",
            steps: 5,
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`异步方法调用成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`异步方法调用失败: ${error.message}`, "error");
        }
      });

      streamDataBtn.addEventListener("click", async () => {
        try {
          const result = await bridge.call("streamData", {
            count: 10, // 生成10条数据
            interval: 100, // 每100ms生成一条数据
          });
          asyncResultEl.textContent = JSON.stringify(result, null, 2);
          log(`流式数据生成成功: ${JSON.stringify(result)}`, "success");
        } catch (error) {
          asyncResultEl.textContent = `错误: ${error.message}`;
          log(`流式数据生成失败: ${error.message}`, "error");
        }
      });

      // 页面加载完成后自动初始化
      window.addEventListener("load", async () => {
        log("页面加载完成，开始初始化连接...");
        try {
          await bridge.init();
          log("连接初始化成功", "success");
        } catch (error) {
          log(`连接初始化失败: ${error.message}`, "error");
        }
      });

      // 定期发送心跳
      setInterval(() => {
        if (bridge.getConnectionStatus()) {
          bridge.emit("heartbeat", { timestamp: Date.now() });
        }
      }, 30000); // 每30秒发送一次心跳
    </script>
  </body>
</html>
